from flask import Flask, render_template, request, redirect, url_for, session, send_from_directory
import sqlite3
from werkzeug.security import generate_password_hash, check_password_hash

app = Flask(__name__)
app.secret_key = 'your-secret-key-here'

def get_db():
    conn = sqlite3.connect('search_engine.db')
    conn.row_factory = sqlite3.Row
    return conn

@app.route('/')
def index():
    return render_template('search.html')

@app.route('/search')
def search():
    query = request.args.get('q', '')
    page = int(request.args.get('page', 1))
    per_page = 10

    conn = get_db()
    cursor = conn.cursor()
    
    # 简单搜索逻辑（可扩展为全文搜索）
    cursor.execute("""
        SELECT *, 
        (title LIKE ?) * 2 + (content LIKE ?) AS relevance 
        FROM pages 
        WHERE title LIKE ? OR content LIKE ?
        ORDER BY relevance DESC, id DESC
        LIMIT ? OFFSET ?
    """, (f'%{query}%', f'%{query}%', f'%{query}%', f'%{query}%', per_page, (page-1)*per_page))
    
    results = cursor.fetchall()
    return render_template('results.html', results=results, query=query, page=page)

@app.route('/admin/login', methods=['GET', 'POST'])
def admin_login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        
        conn = get_db()
        user = conn.execute(
            'SELECT * FROM users WHERE username = ?', 
            (username,)
        ).fetchone()
        
        if user and check_password_hash(user['password'], password):
            session['admin_logged_in'] = True
            return redirect(url_for('admin_dashboard'))
    
    return render_template('admin/login.html')

@app.route('/admin/dashboard')
def admin_dashboard():
    if not session.get('admin_logged_in'):
        return redirect(url_for('admin_login'))
    
    conn = get_db()
    stats = conn.execute("""
        SELECT 
            (SELECT COUNT(*) FROM pages) AS page_count,
            (SELECT COUNT(*) FROM crawler_queue) AS queue_count
    """).fetchone()
    
    return render_template('admin/dashboard.html', stats=stats)

@app.route('/tencent8533094206726755089.txt')
def manifest():
    return send_from_directory('./', 'tencent8533094206726755089.txt')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5200, debug=True)